#!/bin/bash
# MLX Caption launcher: one-time runtime setup, then the native desktop window.
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
SUP="$HOME/Library/Application Support/MLX-Caption"
RT="$SUP/runtime"
LOG="$HOME/Library/Logs/MLX-Caption.log"
VERSION="$(cat "$RES/version")"
mkdir -p "$SUP" "$(dirname "$LOG")"

alert() { osascript -e "display alert \"MLX Caption\" message \"$1\" as critical" >/dev/null 2>&1; }
notify() { osascript -e "display notification \"$1\" with title \"MLX Caption\"" >/dev/null 2>&1; }

if [[ "$(uname -m)" != "arm64" ]]; then
  alert "MLX Caption requires a Mac with Apple silicon (M1 or newer)."; exit 1
fi
if [[ "$(sw_vers -productVersion | cut -d. -f1)" -lt 14 ]]; then
  alert "MLX Caption requires macOS 14 Sonoma or newer."; exit 1
fi

if [[ "$(cat "$RT/.version" 2>/dev/null)" != "$VERSION" ]]; then
  LOCK="$SUP/.setup-lock"
  if ! mkdir "$LOCK" 2>/dev/null; then
    # Another launch is already installing (or a stale lock from a crash older than 30 min).
    if [[ -n "$(find "$LOCK" -maxdepth 0 -mmin +30 2>/dev/null)" ]]; then rm -rf "$LOCK"; mkdir "$LOCK"
    else notify "Still setting up — MLX Caption will open automatically when ready."; exit 0; fi
  fi
  trap 'rm -rf "$LOCK"' EXIT
  if [[ -z "${MLXCAPTION_NONINTERACTIVE:-}" ]]; then
    osascript -e 'display dialog "Welcome to MLX Caption!\n\nThe first time it opens, MLX Caption installs its components (about 1 GB). This takes 2–5 minutes with a good connection, and the app opens automatically when ready.\n\nAfter that, you will download the AI models from inside the app." buttons {"Cancel", "Set Up"} default button "Set Up" with title "MLX Caption" with icon note' >/dev/null 2>&1 || exit 0
  fi
  notify "Setting up… this takes a few minutes. The app will open when ready."
  {
    echo "=== Setup $VERSION $(date) ==="
    # Fetch the pinned uv installer from its official GitHub release and verify its checksum.
    UV_VER="0.13.6"
    UV_SHA="60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472"
    UVBIN="$SUP/uv-$UV_VER/uv"
    if [[ ! -x "$UVBIN" ]]; then
      TGZ="$SUP/uv-$UV_VER.tar.gz"
      curl -fL --retry 10 --retry-all-errors -C - -o "$TGZ" \
        "https://github.com/astral-sh/uv/releases/download/$UV_VER/uv-aarch64-apple-darwin.tar.gz" &&
      [[ "$(shasum -a 256 "$TGZ" | cut -d' ' -f1)" == "$UV_SHA" ]] &&
      mkdir -p "$SUP/uv-$UV_VER" &&
      tar -xzf "$TGZ" -C "$SUP/uv-$UV_VER" --strip-components 1 &&
      rm -f "$TGZ" || { echo "uv download failed or checksum mismatch"; rm -f "$TGZ"; }
    fi
    export UV_PYTHON_INSTALL_DIR="$SUP/python" UV_CACHE_DIR="$SUP/uv-cache"
    "$UVBIN" venv --python 3.12 --clear "$RT" &&
    "$UVBIN" pip install --python "$RT/bin/python" -r "$RES/requirements.lock" "$RES"/mlxcaption-*.whl &&
    "$RT/bin/python" -c "import mlx.core, mlxcaption.server, webview" &&
    echo "$VERSION" > "$RT/.version"
  } >>"$LOG" 2>&1
  if [[ "$(cat "$RT/.version" 2>/dev/null)" != "$VERSION" ]]; then
    alert "Setup could not finish. Please check your internet connection and open MLX Caption again (progress is kept).\n\nDetails: ~/Library/Logs/MLX-Caption.log"
    exit 1
  fi
  notify "Setup complete — opening MLX Caption."
fi

exec "$RT/bin/python" -m mlxcaption desktop >>"$LOG" 2>&1
